package com.gome.postwoman;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class Store implements Serializable {
    private static final  org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WSServer.class);

    List<String> history;
    LinkedHashMap<String,String> favorites;

    static Store instance;

    static File file = new File("store.obj");

    static {
        if(file.exists()){
            log.info("读取配置文件");
            try (InputStream in = new FileInputStream("store.obj")){
                try (ObjectInputStream objIn = new ObjectInputStream(in)){
                    instance = (Store) objIn.readObject();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else {
            log.info("未发现配置文件");
            instance = new Store();
            instance.history = new ArrayList<>();
            instance.favorites = new LinkedHashMap<>();
            try {
                file.createNewFile();
                log.info("初始化默认配置文件");
                update();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static List<String> getHistory(){
        return instance.history;
    }

    public static LinkedHashMap<String,String> getFavorites(){
        return instance.favorites;
    }

    public static void update(){
        try (OutputStream out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out)){
            objOut.writeObject(instance);
            log.info("更新配置文件");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
